package com.app.baselibrary.http.flow
import com.app.baselibrary.http.HttpConfig
import retrofit2.*
import java.lang.reflect.Type

/**
 * flow callAdapter
 */
class FlowCallAdapterFactory<E: Throwable>
    constructor(private val exceptionConvert: HttpFlow.ExceptionConvert<E>?) : CallAdapter.Factory(){


    companion object {

        fun <E: Throwable> create(exceptionConvert: HttpFlow.ExceptionConvert<E>? = null)
                = FlowCallAdapterFactory(exceptionConvert)
    }


    override fun get(returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit): CallAdapter<*, *>? {
        return when {
            getRawType(returnType) != HttpFlow::class.java -> {
                null
            }
            else -> {
                FlowCallAdapter<E>(String::class.java, exceptionConvert)
            }
        }
    }

}


/**
 * adapter
 */
class FlowCallAdapter<E: Throwable> constructor(private val responseType: Type,
       private val exceptionConvert: HttpFlow.ExceptionConvert<E>?)
    : CallAdapter<Any, HttpFlow>{
    override fun adapt(call: Call<Any>): HttpFlow {
        val executeCall = HttpConfig.okHttpClient.newCall(call.request())
        return HttpFlow(executeCall, exceptionConvert as HttpFlow.ExceptionConvert<Throwable>)
    }

    override fun responseType(): Type {
        return responseType
    }

}